<template>
	<view
		class="flex flex-row border-b b-color-1 py-3-1 text-hide"
		:style="{ 'border-bottom-width': border ? '1px' : 0 }"
		:class="{ 'items-center': type !== 'textarea' }"
	>
		<view
			class="mr-3-1 row-center"
			v-if="label"
			:class="{ 'items-start': type === 'textarea' }"
			:style="labelWidth ? { width: labelWidth + 'px' } : {}"
		>
			<sl-icon :name="icon" v-if="icon" class="mr-1-3" />
			<text class="text-title color-main">{{ label }}</text>
			<text class="text-l color-error ml-1" v-if="requiredMark">*</text>
		</view>
		<view class="flex-1" @click="clickContent">
			<text
				class="text-title"
				v-if="showText"
				:class="[showTextCls ? showTextCls : disabled ? 'color-disable' : 'color-main']"
			>
				{{ showText }}
			</text>
			<switch
				v-else-if="type === 'switch'"
				:color="SlStyle.primaryColor"
				:checked="formItemValue"
				@change="switchChange"
			/>
			<MediaListUpload v-else-if="type === 'image'" :num="1" ref="imgList" />
			<view v-else-if="type === 'chooseLocation'" class="row-center pr-3-1">
				<view class="flex-1 mr-3">
					<text v-if="chooseText" class="text-title color-main">{{ chooseText }}</text>
					<text v-else class="color-disable text-title">{{ placeholder }}</text>
				</view>
				<Icon v-if="chooseIcon" :name="chooseIcon" extraClass="color-secondary" />
				<text v-else class="iconfont icon-you text-l color-secondary"></text>
			</view>
			<view v-else-if="type === 'textarea'" class="text-left">
				<DetailTextarea
					:placeholder="placeholder"
					:maxlength="maxlength"
					extraClass="mr-3-1"
					:extraStyle="
						'min-height:160rpx;padding-top:4rpx;' + (textAreaHeight ? 'height:' + textAreaHeight + 'rpx' : '')
					"
					@change="textareaChange"
					ref="textarea"
				></DetailTextarea>
			</view>
			<view
				v-else-if="type === 'customChoose' || type === 'picker' || type === 'region' || type === 'treePicker'"
				class="row-center pr-3-1"
			>
				<view class="flex-1 mr-3">
					<text v-if="loading" class="text-m color-secondary">加载中...</text>
					<text v-else-if="formItemValue && type === 'customChoose'" class="text-title color-main">
						{{ formItemValue }}
					</text>
					<text
						v-else-if="chooseText && (type === 'picker' || type === 'region' || type === 'treePicker')"
						class="text-title color-main"
					>
						{{ chooseText }}
					</text>
					<text v-else class="color-disable text-title">{{ placeholder }}</text>
				</view>
				<view
					v-if="showClear && !loading && (!isNullOrUndefOrEmpty(formItemValue) || chooseText)"
					class="py-1 px-2"
					hover-class="bg-color-2"
					hover-stay-time="50"
					hover-start-time="0"
					@click.stop="clearValue"
				>
					<text class="iconfont icon-guanbi color-secondary text-l"></text>
				</view>
				<view
					v-if="extraIcon"
					@click.stop="$emit('touchIcon')"
					class="px-1"
					hover-class="opacity-80"
					hover-stay-time="50"
					hover-start-time="0"
				>
					<Icon :name="extraIcon" extraClass="color-secondary" />
				</view>
				<view v-if="chooseIcon"> <Icon :name="chooseIcon" extraClass="color-secondary" /> </view>
				<text v-else class="iconfont icon-you text-l color-secondary"></text>
			</view>
			<lib-datetime-picker
				v-model="formItemValue"
				v-bind="options"
				v-else-if="type === 'datetime' || type === 'date'"
				:hideSecond="true"
			>
				<view class="row-center pr-3-1">
					<view class="flex-1 mr-3">
						<text v-if="formItemValue" class="text-title color-main">{{ formItemValue }}</text>
						<text v-else class="color-disable text-title">{{ placeholder }}</text>
					</view>
					<text class="iconfont icon-you text-l color-secondary"></text>
				</view>
			</lib-datetime-picker>
			<view class="text-right pr-3-1" v-else-if="type === 'numberbox'">
				<c-numberbox v-model="formItemValue" :disabled="disabled" />
			</view>
			<input
				v-else
				class="text-title"
				:type="inputType || 'text'"
				:placeholder="placeholder"
				:placeholder-style="'color: ' + SlStyle.disableColor"
				:maxlength="maxlength"
				v-model="formItemValue"
			/>
		</view>
		<view
			v-if="extraIcon && type === 'text'"
			@click.stop="$emit('touchIcon')"
			class="pr-3-1 pl-1-3 ml-1-3 border-l b-color-1"
			hover-class="opacity-80"
			hover-stay-time="50"
			hover-start-time="0"
		>
			<Icon :name="extraIcon" extraClass="color-secondary" />
		</view>
		<ItemPicker v-if="type === 'picker'" ref="itemPicker" :data="data" @pick="onPick" />
		<TreePicker
			v-if="type === 'region'"
			ref="treePicker"
			title="选择区域"
			@pick="onTreePick"
			:getData="getRegionData"
			:fieldNames="{ key: 'regionCode', title: 'regionName' }"
		/>
		<TreePicker
			v-if="type === 'treePicker'"
			v-bind="options"
			ref="treePicker"
			:title="label"
			@pick="onTreePick"
			:data="data"
		/>
	</view>
</template>

<script>
import { ref, watch, nextTick, onMounted } from 'vue';
import ItemPicker from '../item-picker/item-picker.vue';
import TreePicker from '../tree-picker/tree-picker.vue';
import MediaListUpload from '../media-list-upload/media-list-upload.vue';
import DetailTextarea from '../detail-textarea/detail-textarea.vue';
import SlStyle from '../../../style/style.js';
import Icon from '../../business/icon/icon.vue';
import { getRules, verifyByRules } from '../../../utils/verify.js';
import { isNullOrUndefOrEmpty } from '../../../utils/common.js';
export default {
	components: {
		MediaListUpload,
		DetailTextarea,
		ItemPicker,
		Icon,
		TreePicker,
	},
	props: {
		icon: String,
		label: String,
		labelWidth: {
			default: uni.upx2px(200),
			type: Number,
		},
		subLabel: String,
		placeholder: String,
		showText: String,
		showTextCls: String,
		border: {
			default: true,
			type: Boolean,
		},
		//text picker customPicker textarea chooseLocation switch customChoose datetime date numberbox region
		type: String,
		inputType: String,
		//picker data
		data: Array,
		maxlength: {
			type: Number,
			default: 200,
		},
		modelValue: [String, Number, Array, Object],
		chooseIcon: String,
		extraIcon: String,
		getRegionData: Function,
		loading: Boolean,
		showClear: Boolean,
		textAreaHeight: Number,
		disabled: Boolean,
		//
		requiredMark: Boolean,
		required: Boolean,
		requiredMes: String,
		pattern: String,
		patternMes: String,
		options: {
			type: Object,
			default: {},
		},
	},
	setup(props, ctx) {
		const imgList = ref();
		const textarea = ref();
		const itemPicker = ref();
		const treePicker = ref();
		const chooseText = ref('');
		const formItemValue = ref();
		let isTriggerWatch = true;
		watch(formItemValue, (v) => {
			if (!isTriggerWatch) return;
			isTriggerPropWatch = false;
			ctx.emit('update:modelValue', v);
			nextTick(() => {
				isTriggerPropWatch = true;
			});
		});
		let isTriggerPropWatch = true;
		const rules = getRules({
			required: props.required,
			requiredMes: props.requiredMes,
			pattern: props.pattern,
			patternMes: props.patternMes,
		});
		function handleValue(value) {
			isTriggerWatch = false;
			switch (props.type) {
				case 'picker':
					if (isNullOrUndefOrEmpty(value)) {
						chooseText.value = '';
					} else {
						const item = props.data.find((el) => el.value === value);
						if (item) {
							chooseText.value = item.text;
						}
					}
					formItemValue.value = value;
					break;
				case 'treePicker':
				case 'region':
					chooseText.value = value;
					break;
				case 'chooseLocation':
					//{address: "广东省佛山市顺德区兴隆十路8号", latitude: 22.980202, name: "广东申菱环境系统股份有限公司", errMsg: "chooseLocation:ok", longitude: 113.21539}
					chooseText.value = value.address;
					formItemValue.value = value;
					break;
				case 'textarea':
					console.log('============>form item setContent', value);
					textarea.value.setContent(value);
				default:
					formItemValue.value = value;
					break;
			}
			nextTick(() => {
				isTriggerWatch = true;
			});
		}
		watch(
			() => props.modelValue,
			(value) => {
				if (!isTriggerPropWatch) return;
				// console.log("===========>form-item prop's value change", value);
				handleValue(value);
			}
		);
		onMounted(() => {
			handleValue(props.modelValue);
		});
		if (props.type === 'picker') {
			watch(
				() => props.data,
				() => {
					handleValue(props.modelValue);
				}
			);
		}
		function chooseLocation() {
			// const e = {
			// 	address: '广东省佛山市顺德区兴隆十路8号',
			// 	latitude: 22.980202,
			// 	name: '广东申菱环境系统股份有限公司',
			// 	errMsg: 'chooseLocation:ok',
			// 	longitude: 113.21539,
			// };
			// chooseText.value = e.address;
			// formItemValue.value = e;
			uni.chooseLocation({
				success(e) {
					//{address: "广东省佛山市顺德区兴隆十路8号", latitude: 22.980202, name: "广东申菱环境系统股份有限公司", errMsg: "chooseLocation:ok", longitude: 113.21539}
					chooseText.value = e.address;
					formItemValue.value = e;
				},
			});
		}
		return {
			chooseText,
			formItemValue,
			SlStyle,
			onPick(e) {
				if (e.item) {
					formItemValue.value = e.value;
					chooseText.value = e.item.text;
					ctx.emit('pick', {
						value: e.value,
						text: e.item.text,
						item: e.item,
					});
				}
			},
			onTreePick(item) {
				const { keys, titles } = item;
				chooseText.value = titles[titles.length - 1];
				// chooseText.value = titles.join('-');
				formItemValue.value = chooseText.value;
				ctx.emit('pick', {
					value: keys,
					text: titles,
					item,
				});
			},
			clickContent() {
				if (props.disabled) return;
				ctx.emit('touch');
				if (props.type === 'chooseLocation') {
					uni.showLoading({
						title: '加载中',
						mask: true,
					});
					uni.getSetting({
						success(res) {
							if (!res.authSetting['scope.userLocation']) {
								uni.authorize({
									scope: 'scope.userLocation',
									success() {
										chooseLocation();
									},
								});
							} else {
								chooseLocation();
							}
						},
						complete() {
							uni.hideLoading();
						},
					});
				} else if (props.type === 'picker') {
					itemPicker.value.open({
						value: formItemValue.value,
					});
				} else if (props.type === 'region' || props.type === 'treePicker') {
					treePicker.value.open();
				}
			},
			onChoose(items) {
				formItemValue.value = items;
				const texts = items.map((el) => el.text);
				chooseText.value = texts.join(',');
			},
			async uploadImg() {
				if (props.type === 'image') {
					return await imgList.value.upload1by1();
				}
			},
			validate() {
				let mes = verifyByRules(formItemValue.value, rules);
				if (mes) {
					getApp().globalData.toast(mes);
					return false;
				}
				return true;
			},
			getText() {
				return chooseText.value;
			},
			switchChange(e) {
				formItemValue.value = e.target.value;
			},
			textareaChange(e) {
				formItemValue.value = e;
			},
			clearValue() {
				formItemValue.value = '';
				chooseText.value = '';
			},
			isNullOrUndefOrEmpty,
			imgList,
			textarea,
			itemPicker,
			treePicker,
		};
	},
};
</script>

<style></style>
